package cn.tedu.storage.tcc;

import cn.tedu.storage.entity.Storage;
import cn.tedu.storage.mapper.StorageMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
@Component
public class StorageTccActionImpl implements StorageTccAction {
    @Resource
    private StorageMapper storageMapper;
    @Transactional
    @Override
    public boolean prepare(BusinessActionContext context, Long productId, Integer count) {
        //判断有没有足够库存
        Storage storage = storageMapper.selectByProductId(productId);
        if (storage.getResidue()<count){
            throw new RuntimeException("库存不足");
        }
        ResultHolder.setResult(StorageTccAction.class,context.getXid(),"p");
        storageMapper.updateResidueToFrozen(productId, count);
        return true;
    }

    @Transactional
    @Override
    public boolean commit(BusinessActionContext context) {
        if (ResultHolder.getResult(StorageTccAction.class, context.getXid()) == null){
            return true;
        }
        Long productId = Long.valueOf(context.getActionContext("productId").toString());
        Integer count = Integer.valueOf(context.getActionContext("count").toString());
        storageMapper.updateFrozenToUsed(productId, count);
        ResultHolder.removeResult(StorageTccAction.class, context.getXid());
        return true;
    }

    @Transactional
    @Override
    public boolean rollback(BusinessActionContext context) {
        if (ResultHolder.getResult(StorageTccAction.class, context.getXid()) == null){
            return true;
        }
        Long productId = Long.valueOf(context.getActionContext("productId").toString());
        Integer count = Integer.valueOf(context.getActionContext("count").toString());

        storageMapper.updateFrozenToResidue(productId, count);
        ResultHolder.removeResult(StorageTccAction.class, context.getXid());
        return true;
    }
}
